package com.foodcommunity.controller;

import com.foodcommunity.dto.PostCreateDTO;
import com.foodcommunity.entity.User;
import com.foodcommunity.service.CategoryService;
import com.foodcommunity.service.PostService;
import com.foodcommunity.service.TagService;
import com.foodcommunity.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/posts")
public class PostController {
    
    @Autowired
    private PostService postService;
    
    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private TagService tagService;
    
    @GetMapping("/create")
    public String showCreateForm(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        model.addAttribute("categories", categoryService.getAllCategories());
        model.addAttribute("tags", tagService.getAllTags());
        return "post/create";
    }
    
    @PostMapping("/create")
    public String createPost(PostCreateDTO postDTO, HttpSession session, RedirectAttributes redirectAttributes) {
        try {
            // 检查用户是否登录
            User user = (User) session.getAttribute("user");
            if (user == null) {
                redirectAttributes.addFlashAttribute("error", "请先登录");
                return "redirect:/login";
            }
            
            // 处理图片上传
            List<String> imageUrls = new ArrayList<>();
            if (postDTO.getImageFiles() != null) {
                for (MultipartFile file : postDTO.getImageFiles()) {
                    if (file != null && !file.isEmpty()) {
                        String imageUrl = FileUploadUtil.saveFile(file);
                        imageUrls.add(imageUrl);
                    }
                }
            }
            postDTO.setImages(imageUrls);

            // 设置用户ID
            postService.createPost(postDTO);
            redirectAttributes.addFlashAttribute("message", "文章发布成功！");
            return "redirect:/posts";
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("error", "文章发布失败：" + e.getMessage());
            return "redirect:/posts/create";
        }
    }
} 